<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 靠右的按钮 -->
      <page-tools>
        <template v-slot:after>
          <el-button
            type="primary"
            size="small"
            @click="btnAdd(0, 1)"
          >添加权限</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-table
        border
        :data="permissionList"
        row-key="id"
        stripe
        default-expand-all
      >
        <el-table-column align="center" prop="name" label="名称" />
        <el-table-column align="center" prop="code" label="标识" />
        <el-table-column align="center" prop="description" label="描述" />
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <el-button type="text" @click="btnAdd(row.id)">添加</el-button>
            <el-button type="text" @click="btnEdit(row.id)">编辑</el-button>
            <el-button type="text" @click="btnDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <AddPerm
      :show-dialog.sync="showDialog"
      :form-data="formData"
      @reload="getPermissionListFn"
    />
  </div>
</template>

<script>
import {
  getPermissionListAPI,
  delPermissionAPI,
  getPermissionDetailAPI
} from '@/api/permission'
import { formatTree } from '@/utils/tree'
import AddPerm from './components/add-permission.vue'

export default {
  components: { AddPerm },
  data() {
    return {
      permissionList: [],
      showDialog: false,
      formData: {}
    }
  },
  watch: {
    showDialog(val) {
      if (!val) this.formData = {}
    }
  },
  created() {
    this.getPermissionListFn()
  },
  methods: {
    async getPermissionListFn() {
      try {
        const res = await getPermissionListAPI()
        this.permissionList = formatTree(res, '0')
      } catch (e) {
        console.log(e)
      }
    },
    btnAdd(id, type) {
      this.showDialog = true
      this.formData.pid = id
      this.formData.type = type
    },
    async btnEdit(id) {
      const res = await getPermissionDetailAPI(id)
      this.formData = res
      this.showDialog = true
    },
    async btnDel(id) {
      try {
        await this.$confirm('确认删除？')
        await delPermissionAPI(id)
        this.$message.success('操作成功')
        this.getPermissionListFn()
      } catch (e) {
        this.$message.info(e)
      }
    }
  }
}
</script>
